"""
from flask import Blueprint, render_template, session, redirect, url_for

# 创建主模块蓝图
main_bp = Blueprint('main', __name__, url_prefix='/', template_folder='../templates/main')

# 主页路由（需要登录才能访问）
@main_bp.route('home')
def home():
    if not session.get('logged_in'):
        return redirect(url_for('auth.login'))  # 未登录跳转到登录页
    return render_template('home.html', username=session.get('username'))

# 根路径重定向到登录页
@main_bp.route('')
def index():
    return redirect(url_for('auth.login'))

"""

from flask import Blueprint, render_template, session, redirect, url_for,request, flash

from utils.db import get_store_performance  # 导入新函数
# 创建主模块蓝图
main_bp = Blueprint('main', __name__, url_prefix='/', template_folder='../templates/main')

# 主页路由（需要登录才能访问）
@main_bp.route('home')
def home():
    if not session.get('logged_in'):
        return redirect(url_for('auth.login'))  # 未登录跳转到登录页
    return render_template('home.html', username=session.get('username'))




# 库存查询路由
@main_bp.route('inventory')
def inventory():
    if not session.get('logged_in'):
        return redirect(url_for('auth.login'))
    return render_template('inventory.html', username=session.get('username'))

# 盘点单查询路由
@main_bp.route('inventory-check')
def inventory_check():
    if not session.get('logged_in'):
        return redirect(url_for('auth.login'))
    return render_template('inventory_check.html', username=session.get('username'))

# 根路径重定向到登录页
@main_bp.route('')
def index():
    return redirect(url_for('auth.login'))

# 业绩查询路由
@main_bp.route('performance', methods=['GET', 'POST'])
def performance():
    if not session.get('logged_in'):
        return redirect(url_for('auth.login'))
        
    if request.method == 'GET':
        # 显示查询表单
        return render_template('performance.html')
    else:
        # 处理表单提交
        start_date = request.form.get('start_date')
        end_date = request.form.get('end_date')
        
        if not start_date or not end_date:
            flash('请选择起始时间和结束时间')
            return render_template('performance.html', username=session.get('username'))
            
        try:
            # 获取业绩数据
            performance_data = get_store_performance(start_date, end_date)
            return render_template(
                'performance.html', 
                username=session.get('username'),
                performance_data=performance_data,
                start_date=start_date,
                end_date=end_date
            )
        except Exception as e:
            flash(f'查询失败: {str(e)}')
            return render_template('performance.html', username=session.get('username'))